package uit.shoeshop.model;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import uit.shoeshop.dto.ProductDTO;
import uit.shoeshop.dao.ProductDAO;
import uit.shoeshop.lib.Util;

public class CheckoutModel {
	private Integer totalPrice;
	public CheckoutModel(){
		
	}
	
	public HashMap<Integer,ProductDTO> getAllProductInCart(HashMap<Integer,Integer> cart) throws SQLException{
		HashMap<Integer,ProductDTO> products = new HashMap<Integer,ProductDTO>();
		
		ProductDAO productDAO = new ProductDAO();
		ProductDTO product;
		Integer totalPriceTemp = 0;
       	Set set = cart.entrySet();
    	Iterator i = set.iterator();
    	while(i.hasNext()) {
        	Map.Entry me = (Map.Entry)i.next();
        	Integer key = Integer.parseInt(me.getKey().toString());
        	Integer value = Integer.parseInt(me.getValue().toString());
        	product = productDAO.getProductDetail(key);
        	if(product != null){
        		products.put(key,product);
        		totalPriceTemp += product.getPrice()*value;
        	}
    	}
		setTotalPrice(totalPriceTemp);
		return products;
	}
	
	public HashMap<Integer,Integer> getRawCart(HttpServletRequest request) throws SQLException{
		
    	HashMap<Integer,Integer> cart;
    	Object obj = uit.shoeshop.lib.Util.getSessions("cart",request);
    	
    	cart = (HashMap<Integer, Integer>) obj;

    
    	return cart;
	}

	public int changeQty(int productId,int qty,HttpServletRequest request) throws SQLException{
    	HashMap<Integer,Integer> cart ;
    	Object obj = uit.shoeshop.lib.Util.getSessions("cart",request);
    	
    	ProductDAO productDAO = new ProductDAO();
		ProductDTO product;
		product = productDAO.getProductDetail(productId);
		if(product == null){
			return -1;
		}else{
			if(qty > product.getIn_stock()){
				return 0;
			}
	    	cart = (HashMap<Integer, Integer>) obj;
	    		try{
	    			cart.put(productId, qty);
	    			Util.addSessions("cart", cart, request);
	    		}catch(Exception e){
	    			return -1;
	    		}
		}
		return 1;
	}
	
	public boolean deleteProductInCart(int productId,HttpServletRequest request){
    	HashMap<Integer,Integer> cart;
    	Object obj = uit.shoeshop.lib.Util.getSessions("cart",request);

    	cart = (HashMap<Integer, Integer>) obj;
    		try{
    			cart.remove(productId);
    			Util.addSessions("cart", cart, request);
    		}catch(Exception e){
    			return false;
    		}

		return true;
	}	
	/**
	 * @param totalPrice the totalPrice to set
	 */
	public void setTotalPrice(Integer totalPrice) {
		this.totalPrice = totalPrice;
	}

	/**
	 * @return the totalPrice
	 */
	public Integer getTotalPrice() {
		return totalPrice;
	}

}